const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const compression = require('compression');
const authRoutes = require('./server/routes/auth');
const taskRoutes = require('./server/routes/tasks');

const app = express();

// 启用gzip压缩
app.use(compression());

// 中间件配置
app.use(cors());
app.use(express.json());

// 处理favicon请求
app.get('/favicon.ico', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'favicon.ico'));
});

// MongoDB连接配置优化
const mongoOptions = {
  maxPoolSize: 10,
  minPoolSize: 5,
  connectTimeoutMS: 5000,
  socketTimeoutMS: 10000,
  family: 4
};

// 连接MongoDB
console.log('Connecting to MongoDB...');
mongoose.connect('mongodb://127.0.0.1:27017/green_planet', mongoOptions)
  .then(() => {
    console.log('MongoDB connected successfully!');
    // 连接成功后初始化任务数据
    // initializeTasks();
  })
  .catch(err => {
    console.error('MongoDB connection failed:', err);
    console.log('Continuing to start server, but some features may be unavailable...');
  });

// 定义任务模型
const taskSchema = new mongoose.Schema({
  title: { 
    type: String, 
    required: true 
  },
  description: { 
    type: String, 
    required: true 
  },
  type: { 
    type: String, 
    enum: ['daily', 'weekly', 'monthly', 'custom', 'challenge'],
    required: true 
  },
  reward: {
    greenEnergy: { type: Number, required: true },
    carbonReduction: { type: Number, required: true }
  },
  progress: { 
    type: Number, 
    default: 0 
  },
  completed: { 
    type: Boolean, 
    default: false 
  },
  criteria: {
    type: { type: String, required: true },
    target: { type: Number, required: true },
    current: { type: Number, default: 0 }
  },
  carbonFootprintCategory: {
    type: String,
    enum: ['all', 'high', 'low'],
    default: 'all'
  }
}, { timestamps: true });

// 确保模型只定义一次
let Task;
try {
  Task = mongoose.model('Task');
} catch (e) {
  Task = mongoose.model('Task', taskSchema);
}

// // 示例任务数据（仅用于初始化）
// const baseTasks = [
//   {
//     title: '减少肉类摄入',
//     description: '本周尝试素食一天，减少与肉类生产相关的碳排放',
//     type: 'challenge',
//     reward: {
//       greenEnergy: 80,
//       carbonReduction: 4
//     },
//     progress: 0,
//     completed: false,
//     criteria: {
//       type: 'action',
//       target: 1,
//       current: 0
//     },
//     carbonFootprintCategory: 'all'
//   },
//   // 其他任务...
// ];

// const highCarbonTasks = [
//   {
//     title: '交通减碳计划',
//     description: '制定并实施个人交通减碳计划，减少私家车使用',
//     type: 'challenge',
//     reward: {
//       greenEnergy: 150,
//       carbonReduction: 12
//     },
//     progress: 0,
//     completed: false,
//     criteria: {
//       type: 'action',
//       target: 1,
//       current: 0
//     },
//     carbonFootprintCategory: 'high'
//   },
//   // 其他任务...
// ];

// const lowCarbonTasks = [
//   {
//     title: '环保大使',
//     description: '向朋友或家人分享你的环保经验，影响更多人',
//     type: 'challenge',
//     reward: {
//       greenEnergy: 120,
//       carbonReduction: 6
//     },
//     progress: 0,
//     completed: false,
//     criteria: {
//       type: 'action',
//       target: 3,
//       current: 0
//     },
//     carbonFootprintCategory: 'low'
//   },
//   // 其他任务...
// ];

// // 初始化任务数据（仅用于初始化）
// async function initializeTasks() {
//   try {
//     const tasks = await Task.find();
//     if (tasks.length === 0) {
//       console.log('初始化任务数据...');
//       await Task.insertMany([...baseTasks, ...highCarbonTasks, ...lowCarbonTasks]);
//       console.log('任务数据初始化完成');
//     } else {
//       console.log('任务数据已存在，跳过初始化');
//     }
//   } catch (error) {
//     console.error('初始化任务数据失败:', error);
//   }
// }

// API路由
app.use('/api/auth', authRoutes);
// app.use('/api/tasks', taskRoutes);

// API端点：获取个性化任务
app.get('/api/tasks', async (req, res) => {
  const { carbonFootprint, userId } = req.query;

  try {
    let query = {};
    
    // 根据碳足迹值筛选任务
    if (carbonFootprint) {
      if (carbonFootprint > 30) {
        query.carbonFootprintCategory = { $in: ['base', 'high'] };
      } else if (carbonFootprint < 15) {
        query.carbonFootprintCategory = { $in: ['base', 'low'] };
      } else {
        query.carbonFootprintCategory = 'all';
      }
    }

    const tasks = await Task.find(query);
    
    const formattedTasks = tasks.map(task => ({
      ...task.toObject(),
      id: task._id.toString()
    }));

    res.json(formattedTasks);
  } catch (error) {
    console.error('Error fetching tasks:', error);
    res.status(500).json({ error: '获取任务失败' });
  }
});

// // 单独的API端点：获取预定义任务列表
// app.get('/api/tasks', async (req, res) => {
//   try {
//     const tasks = await Task.find();
//     res.json(tasks);
//   } catch (error) {
//     console.error('Error fetching predefined tasks:', error);
//     res.status(500).json({ error: 'Internal server error' });
//   }
// });

// 静态文件服务优化
const staticOptions = {
  maxAge: '1d', // 设置缓存时间
  etag: true,
  lastModified: true,
  setHeaders: (res, path) => {
    if (path.endsWith('.html')) {
      res.setHeader('Cache-Control', 'no-cache');
    }
  }
};

console.log('Setting static file directory:', path.join(__dirname, 'build'));
app.use(express.static(path.join(__dirname, 'build'), staticOptions));
app.use(express.static(path.join(__dirname, 'public'), staticOptions));

// 检查build文件夹是否存在
const fs = require('fs');
if (!fs.existsSync(path.join(__dirname, 'build'))) {
  console.error('Error: build folder does not exist!');
  console.log('Please run npm run build to generate the build folder');
}

// 所有其他请求返回React应用
app.get('*', (req, res) => {
  console.log('Request received:', req.path);
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

// 错误处理中间件优化
app.use((err, req, res, next) => {
  console.error('Server error:', err.stack);
  res.status(500).json({ 
    message: 'Server error, please try again later',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, '0.0.0.0', () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`Local access: http://localhost:${PORT}`);
  
  // 获取本机IP地址
  const { networkInterfaces } = require('os');
  const nets = networkInterfaces();
  let localIP = '';
  
  // 遍历网络接口获取IPv4地址
  Object.keys(nets).forEach((name) => {
    for (const net of nets[name]) {
      // 跳过内部IP和非IPv4地址
      if (net.family === 'IPv4' && !net.internal) {
        localIP = net.address;
      }
    }
  });
  
  if (localIP) {
    console.log(`Network access: http://${localIP}:${PORT}`);
  }
});